package com.xzr.hospitalregister.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.xzr.hospitalregister.R;
import com.xzr.hospitalregister.base.BaseActivity;
import com.xzr.hospitalregister.config.HttpUrl;
import com.xzr.hospitalregister.entity.SomethingNeed;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2018/2/24 0024.
 */

public class BBGXActivity extends BaseActivity{
    private String appVersion;//////////////


    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                case 100:
                    if (isUpdate()) {
                        // 显示提示对话框
                        showNoticeDialog();
                        Log.e("TAG","进入版本更新++++++++++++++");
                    } else {
//					Toast.makeText(mContext, R.string.soft_update_no,
//							Toast.LENGTH_LONG).show();
//                        startActivity(new Intent(BBGXActivity.this, PJTYPEActivity.class));
                        Log.e("TAG","没有进入版本更新------------------");
                    }
                    break;
                default:
                    break;
            }
        };
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbgx);
        PackageManager manager = this.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(this.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        appVersion = info.versionName;   //版本名
        /////////////////////
        ////////////////
        SharedPreferences sp = getSharedPreferences("IpSet", MODE_PRIVATE);

        SharedPreferences.Editor edit = sp.edit();
        if (sp.getString("ipValue", null) == null) {
            edit.putString("ipValue", "192.168.0.78:8078");//设置默认ip
        }
//        edit.putString("ipValueCity1", "47.92.82.52:8086");//ip列表中的选择项ip——漯河市
//        edit.putString("ipValueCity2", "122.114.80.116:9999");//ip列表中的选择项ip——沁阳市
        edit.commit();

        SomethingNeed.getInstance().setIp(sp.getString("ipValue", null));
        ///////////////
        ////////////////////

        checkUpdate();////////////////////////
    }

    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        getUpDateInfo();
        // 显示提示对话框
        // showNoticeDialog();
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate() {
        int version = 1;
        try {
            version = Integer.valueOf(strVersion);

        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取当前软件版本
        int versionCode = getVersionCode(this);
        System.out.println("version::::::"+version+"   "+"versionCode:::::"+versionCode);
        Log.e("TAG","获取服务器版本号"+version);
        if (version >versionCode) {
            return true;
        } else {
            startActivity(new Intent(BBGXActivity.this, PJTYPEActivity.class));
            Toast.makeText(BBGXActivity.this,"meiyou +++++++++++++",Toast.LENGTH_LONG).show();
            Log.e("TAG","没有进入版本更新++++++++++++++++");

            finish();
        }
        return false;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 1;
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        try {
            versionCode = context.getPackageManager().getPackageInfo(
                    "com.xzr.hospitalregister", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);
        // 更新
        builder.setPositiveButton(R.string.soft_update_updatebtn,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 显示下载对话框
                        showDownloadDialog();
                    }
                });
        // 稍后更新
        builder.setNegativeButton(R.string.soft_update_later,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(new Intent(BBGXActivity.this, PJTYPEActivity.class));
                        finish();///////////
                    }
                });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.soft_updating);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.soft_update_cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 设置取消状态
                        cancelUpdate = true;

                        startActivity(new Intent(BBGXActivity.this, PJTYPEActivity.class));
                        finish();///////////
                    }
                });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        // 现在文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {

                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory()
                            + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(HttpUrl.LASTEST_VERSION_APK_DOWNLOAD +strVersionCode);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    if(strVersionCode.equals("")){
                        return;
                    }
                    File apkFile = new File(mSavePath,strVersionCode);// 最好是获取的服务器端，文件版本号
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    };

    /**
     * 安装APK文件
     */
//    private void installApk() {
//        File apkfile = new File(mSavePath, strVersionCode);
//        if (!apkfile.exists()) {
//            return;
//        }
//        // 通过Intent安装APK文件
//        Intent i = new Intent(Intent.ACTION_VIEW);
//        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
//                "application/vnd.android.package-archive");
//        this.startActivity(i);
//
//    }
            /////////////
    private void installApk() {
        Log.e("TAG","安装新程序+++++++++++++++++");
        File apkfile = new File(mSavePath, strVersionCode);
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
//        this.startActivity(i);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(i, 0);// 如果用户取消安装的话,
        // 会返回结果,回调方法onActivityResult
        android.os.Process.killProcess(android.os.Process.myPid());
        Log.e("TAG","安装成功新程序+++++++++++++++++");
    }
            //////////////

    String strVersion = null;// 版本号
    String strVersionCode = null;// 版本名称

    public void getUpDateInfo() {
        final String path = HttpUrl.VERSION_CODE_INFO;
        Log.e("TAG","我通过了++++++++++++++++"+path);
        // 创建一个url对象
        new Thread(new Runnable() {
            @Override
            public void run() {
                String line = null;
                BufferedReader reader = null;
                StringBuffer sb = new StringBuffer();
                try {
                    URL url = new URL(path+"?leixing=1");
                    // 通過url对象，创建一个HttpURLConnection对象（连接）
                    HttpURLConnection urlConnection = (HttpURLConnection) url
                            .openConnection();
                    // 通过HttpURLConnection对象，得到InputStream

                    reader = new BufferedReader(new InputStreamReader(
                            urlConnection.getInputStream()));
                    // 使用io流读取文件
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    String strVersiondate = sb.toString();
                    // 开始解析json
                    JSONObject object = new JSONObject(strVersiondate);
                    strVersion = object.get("version").toString();
                    strVersionCode = object.get("versioncode").toString();
                    Log.e("TAG","获取到的版本号"+object.get("version").toString());
                    Log.e("TAG","获取到的版本名称"+object.get("versioncode").toString());
                } catch (Exception e) {
                    Log.i("UpdateManager", "获取服务器数据异常！");
//					e.printStackTrace();
                } finally {
                    try {
                        if (reader != null) {
                            reader.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                mHandler.sendEmptyMessage(100);
            }

        }).start();

    }
    ////////////
    //////////////
}
